package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.exception.DistanceMaxException;
import com.sky.mapper.AddressBookMapper;
import com.sky.properties.BaiduMapProperties;
import com.sky.service.AddressBookService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {
    //https://api.map.baidu.com/geocoding/v3/?address=北京市海淀区上地十街10号&output=json&ak=您的ak&callback=showLocation
    private static final String tempUrl1 = "https://api.map.baidu.com/geocoding/v3/";
    private static final String tempUrl2 = "https://api.map.baidu.com/directionlite/v1/driving";

    //"origin=40.01116,116.339303&destination=39.936404,116.452562&ak=您的AK   //GET请求";
    //"driving?origin=40.01116,116.339303&destination=39.936404,116.452562&ak=您的AK";
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private BaiduMapProperties baiduMapProperties;

    /**
     * 条件查询
     *
     * @param addressBook
     * @return
     */
    public List<AddressBook> list(AddressBook addressBook) {
        return addressBookMapper.list(addressBook);
    }

    /**
     * 新增地址
     *
     * @param addressBook
     */
    public void save(AddressBook addressBook) {
        //String url=tempUrl+"?address="+addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail()+"&output=json&ak="+baiduMapProperties.getAk()+"&callback=showLocation";
        //judgeDistance(addressBook);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public AddressBook getById(Long id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        return addressBook;
    }

    /**
     * 根据id修改地址
     *
     * @param addressBook
     */
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /**
     * 设置默认地址
     *
     * @param addressBook
     */
    @Transactional
    public void setDefault(AddressBook addressBook) {


        //1、将当前用户的所有地址修改为非默认地址 update address_book set is_default = ? where user_id = ?
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateIsDefaultByUserId(addressBook);

        //2、将当前地址改为默认地址 update address_book set is_default = ? where id = ?
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id删除地址
     *
     * @param id
     */
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

    public void judgeDistance(AddressBook addressBook) {
        //String url=tempUrl+"?address="+addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail()+"&output=json&ak="+baiduMapProperties.getAk()+"&callback=showLocation";
        Map<String, String> map1 = new HashMap<>();
        map1.put("address", baiduMapProperties.getAddress());
        map1.put("ak", baiduMapProperties.getAk());
        map1.put("output", "json");
        String json = HttpClientUtil.doGet(tempUrl1, map1);
        JSONObject jsonObject = JSON.parseObject(json);
        Integer status = (Integer) jsonObject.get("status");
        if (status != 0) {
            throw new DistanceMaxException("地图请求出错！");
        }
        String locationString = jsonObject.getString("result");
        jsonObject = JSON.parseObject(locationString);
        String location = jsonObject.getString("location");
        jsonObject = JSONObject.parseObject(location);
        BigDecimal originLat = (BigDecimal) jsonObject.get("lat");
        BigDecimal originLng = (BigDecimal) jsonObject.get("lng");
        //Location location =JSONObject.parseObject((String) jsonObject.get("location"),Location.class) ;
        //纬度值
       /* float originLat = location.getLat();
        //经度值
        float originLng = location.getLng();*/
        map1.put("address", addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        //map.put("callback","showLocation");
        json = HttpClientUtil.doGet(tempUrl1, map1);
        jsonObject = JSON.parseObject(json);
        status = (Integer) jsonObject.get("status");
        if (status != 0) {
            throw new DistanceMaxException("地图请求出错！");
        }
        locationString = jsonObject.getString("result");
        jsonObject = JSON.parseObject(locationString);
        location = jsonObject.getString("location");
        jsonObject = JSONObject.parseObject(location);
        BigDecimal destLat = (BigDecimal) jsonObject.get("lat");
        BigDecimal destLng = (BigDecimal) jsonObject.get("lng");
        Map<String, String> map2 = new HashMap<>();
        map2.put("ak", baiduMapProperties.getAk());
        map2.put("origin", originLat + "," + originLng);
        map2.put("destination", destLat + "," + destLng);
        String jsonDistance = HttpClientUtil.doGet(tempUrl2, map2);
        JSONObject distanceObject = JSON.parseObject(jsonDistance);
        JSONObject resultObject = JSON.parseObject(distanceObject.getString("result"));
        JSONArray routes = resultObject.getJSONArray("routes");
        JSONObject routeOneObject = JSON.parseObject(routes.getString(0));
        String distanceString = routeOneObject.getString("distance");
        double distance = Double.parseDouble(distanceString);
        if (distance > 5000.0d) {
            throw new DistanceMaxException(MessageConstant.DISTANCE_MAX);
        }
    }
}
